<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hello World</title>

    <!-- Bootstrap -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="static/styles.css" rel="stylesheet">
</head>

<body>
    <div class="container">
        <h1>Welcome.</h1>
        <div id="nameInput" class="input-group-lg center-block helloInput">
            <p class="lead">What is your name?</p>
            <input id="user_name" type="text" class="form-control" placeholder="name" aria-describedby="sizing-addon1" value="" />
        </div>
        <p id="response" class="lead text-center"></p>

        <p id="databaseNames" class="lead text-center"></p>
    </div>
    <footer class="footer">
        <div class="container">
            <span><a href="https://console.bluemix.net/docs/tutorials/index.html" target="_blank">Looking for more tutorials?</a></span>
        </div>
    </footer>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="static/antixss.js" type="text/javascript"></script>

    <script>
    	//Submit data when enter key is pressed
        $('#user_name').keydown(function(e) {
        	var name = $('#user_name').val();
            if (e.which == 13 && name.length > 0) { //catch Enter key
                $('#nameInput').hide();
           		$('#response').html("loading...");
            	//POST request to API to create a new visitor entry in the database
                $.ajax({
        				  method: "POST",
        				  url: "./api/visitors",
        				  contentType: "application/json",
        				  data: JSON.stringify({name: name })
        				})
              .done(function(data) {
                  $('#response').html(AntiXSS.sanitizeInput(data));
                  getNames();
              });
            }
        });

        //Retreive all the visitors from the database
        function getNames(){
          $.get("./api/visitors")
              .done(function(data) {
                  if(data.length > 0) {
                    var names = [];
                    data.forEach(function(row) {
                      if(row.doc.name)
                        names.push(AntiXSS.sanitizeInput(row.doc.name));
                    });
                    $('#databaseNames').html("Database contents: " + JSON.stringify(names));
                  }
              });
          }

          //Call getNames on page load.
          getNames();
    </script>
</body>

</html>
